import 'package:dio/dio.dart';
import 'package:mall/core/models/cart_list.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/view_model.dart';

class CartListModel extends ViewModel {
  final Api api;
  String _errorMessage;
  CartList _cartList;

  CartListModel(this.api) : super() {
    _initData();
  }

  String get errorMessage => _errorMessage;

  CartList get cartList => _cartList;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _cartList = await api.cartList(cancelToken);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> refreshData() async {
    try {
      _cartList = await api.cartList(cancelToken);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
